package com.jinly.ryder.account.aspect;

import com.jinly.ryder.account.web.utils.AuthUtil;
import com.jinly.ryder.common.auth.annotation.Auth;
import com.jinly.ryder.common.auth.annotation.AuthParam;
import com.jinly.ryder.common.error.ErrorException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

@Slf4j
@Aspect
@Component
@RequiredArgsConstructor
public class AuthAspect {

    @Around("@annotation(com.jinly.ryder.common.auth.annotation.Auth)")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        checkAuth(pjp);
        Object result = null;
        try {
            result = pjp.proceed();
        } catch (Throwable e) {
            if (!(e instanceof ErrorException)) {
                log.error("AuthAspect err", e);
            }
            throw e;
        }
        return result;
    }

    private void checkAuth(ProceedingJoinPoint pjp) throws NoSuchMethodException {
        Signature signature = pjp.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        String methodName = signature.getName();
        Method method = pjp.getTarget().getClass().getDeclaredMethod(methodName, methodSignature.getMethod().getParameterTypes());
        Auth methodAnn = method.getAnnotation(Auth.class);
        if (methodAnn == null) return;
        String authData = methodAnn.value();
        for (int i = 0; i < method.getParameters().length; i++) {
            AuthParam authParam = method.getParameters()[i].getAnnotation(AuthParam.class);
            if (authParam != null) {
                Object paramValue = pjp.getArgs()[i];
                if (paramValue != null) {
                    if (!isBaseObject(paramValue)) {
                        Field field = ReflectionUtils.findField(paramValue.getClass(), authParam.value());
                        if (field != null) {
                            field.setAccessible(true);
                            paramValue = ReflectionUtils.getField(field, paramValue);
                        }
                    }
                    authData = authData.replaceAll("#\\{" + authParam.value() + "}", paramValue.toString());
                }
            }
        }
        AuthUtil.check(methodAnn.type(), authData, methodAnn.role());
    }

    private boolean isBaseObject(Object paramValue) {
        if (paramValue instanceof Number ||
                paramValue instanceof String
        ) {
            return true;
        }
        return false;
    }
}